//
//  AppDelegate.m
//  TLCityPicker
//
//  Created by yuchen on 15/12/15.
//  Copyright © 2015年 yuchen. All rights reserved.
//

#import "TLCityPickerController.h"
#import "TLCityPickerSearchResultController.h"
#import "TLCityHeaderView.h"
#import "TLCityGroupCell.h"
#import "NSArray+index.h"

@interface TLCityPickerController () <TLCityGroupCellDelegate, TLSearchResultControllerDelegate>

@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) TLCityPickerSearchResultController *searchResultVC;

@property (nonatomic, strong) NSMutableArray *cityData;
@property (nonatomic, strong) NSMutableArray *localCityData;
@property (nonatomic, strong) NSMutableArray *hotCityData;
@property (nonatomic, strong) NSMutableArray *commonCityData;
@property (nonatomic, strong) NSMutableArray *arraySection;
@property (nonatomic, strong) NSArray *souyinArray;

@property (nonatomic, strong) NSMutableDictionary *nameDic;
@property (nonatomic, strong) NSArray *keys;

@property (nonatomic, strong) NSMutableArray *lists;

@end

@implementation TLCityPickerController
@synthesize data = _data;
@synthesize commonCitys = _commonCitys;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"城市选择"];
    //改变导航条背景颜色
    [self.navigationController.navigationBar setBarTintColor:greenColor];
    //改变导航条标题栏字体颜色
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:18],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.automaticallyAdjustsScrollViewInsets = YES;
//    self.definesPresentationContext = YES;

    UIBarButtonItem *cancelBarButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonDown:)];
    [self.navigationItem setLeftBarButtonItem:cancelBarButton];
    
//    [self.tableView setTableHeaderView:self.searchController.searchBar];
    [self.tableView setSectionIndexBackgroundColor:[UIColor clearColor]];
    [self.tableView setSectionIndexColor:[UIColor blackColor]];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.tableView registerClass:[TLCityGroupCell class] forCellReuseIdentifier:@"TLCityGroupCell"];
    [self.tableView registerClass:[TLCityHeaderView class] forHeaderFooterViewReuseIdentifier:@"TLCityHeaderView"];
    [cancelBarButton setTintColor:[UIColor whiteColor]];
    
    [self getCityDic];
}


#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _keys.count + 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section < 2) {
        return 1;
    }
    NSString *key = _keys[section - 2];
    
    NSArray *citys = self.nameDic[key];
    
    return citys.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < 2) {
        TLCityGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLCityGroupCell"];
        if (indexPath.section == 0) {
            [cell setTitle:@"最近访问城市"];
            [cell setCityArray:self.commonCityData];
        }
        else {
            [cell setTitle:@"热门城市"];
            [cell setCityArray:self.hotCityData];
        }
        [cell setDelegate:self];
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];

    NSString *key = _keys[indexPath.section - 2];
    
    NSArray *citys = self.nameDic[key];

    [cell.textLabel setText:citys[indexPath.row]];
    
    return cell;
}

#pragma mark UITableViewDelegate
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section < 2) {
        return nil;
    }
    TLCityHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"TLCityHeaderView"];
    NSString *title = _keys[section - 2];
    [headerView setTitle:title];
    return headerView;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [TLCityGroupCell getCellHeightOfCityArray:self.commonCityData];
    }
    else if (indexPath.section == 1){
        return [TLCityGroupCell getCellHeightOfCityArray:self.hotCityData];
    }
    return 43.0f;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section < 2) {
        return 0.0f;
    }
    return 23.5f;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section < 2) {
        return;
    }
    NSString *key = _keys[indexPath.section - 2];
    
    NSArray *citys = self.nameDic[key];

    [self didSelctedCity:citys[indexPath.row]];
}

- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.arraySection;
}

- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if(index == 0) {
        [self.tableView scrollRectToVisible:self.searchController.searchBar.frame animated:NO];
        return -1;
    }
    return index - 1;
}

#pragma mark TLCityGroupCellDelegate
- (void) cityGroupCellDidSelectCity:(NSString *)city
{
    [self didSelctedCity:city];
}

#pragma mark TLSearchResultControllerDelegate
- (void) searchResultControllerDidSelectCity:(NSString *)city
{
    [self.searchController dismissViewControllerAnimated:YES completion:^{
        
    }];
    [self didSelctedCity:city];
}

#pragma mark - Event Response
- (void) cancelButtonDown:(UIBarButtonItem *)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(cityPickerControllerDidCancel:)]) {
        [_delegate cityPickerControllerDidCancel:self];
    }
}

#pragma mark - Private Methods
- (void) didSelctedCity:(NSString *)city
{
    NSString *ID = @"";
    for (int i = 0; i<_lists.count; i++) {
        NSString *name = [[_lists objectAtIndex:i] objectForKey:@"name"];
        if ([name isEqualToString:city]) {
            ID = [[_lists objectAtIndex:i] objectForKey:@"id"];
        }
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(cityPickerController:didSelectCity:didSelectCityID:)]) {
        [_delegate cityPickerController:self didSelectCity:city didSelectCityID:ID];
    }
    
    if (self.commonCitys.count >= MAX_COMMON_CITY_NUMBER) {
        [self.commonCitys removeLastObject];
    }
    for (NSString *str in self.commonCitys) {
        if ([city isEqualToString:str]) {
            [self.commonCitys removeObject:str];
            break;
        }
    }
    [self.commonCitys addObject:city];
    [[NSUserDefaults standardUserDefaults] setValue:self.commonCitys forKey:COMMON_CITY_DATA_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - Setter
- (void) setCommonCitys:(NSMutableArray *)commonCitys
{
    _commonCitys = commonCitys;
    if (commonCitys != nil && commonCitys.count > 0) {
        [[NSUserDefaults standardUserDefaults] setValue:commonCitys forKey:COMMON_CITY_DATA_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

#pragma mark - Getter 
- (UISearchController *) searchController
{
    if (_searchController == nil) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:self.searchResultVC];
        self.searchController.hidesNavigationBarDuringPresentation = NO;
        [_searchController.searchBar setPlaceholder:@"请输入城市中文名称或拼音"];
        [_searchController.searchBar setBarTintColor:[UIColor colorWithWhite:0.95 alpha:1.0]];
        [_searchController.searchBar sizeToFit];
        [_searchController setSearchResultsUpdater:self.searchResultVC];
        [_searchController.searchBar.layer setBorderWidth:0.5f];
        [_searchController.searchBar.layer setBorderColor:[UIColor colorWithWhite:0.7 alpha:1.0].CGColor];
    }
    return _searchController;
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
//不加的话，UISearchBar返回后会上移


- (TLCityPickerSearchResultController *) searchResultVC
{
    if (_searchResultVC == nil) {
        _searchResultVC = [[TLCityPickerSearchResultController alloc] init];
        _searchResultVC.cityData = self.cityData;
        _searchResultVC.searchResultDelegate = self;
    }
    return _searchResultVC;
}

- (NSMutableArray *) data
{
    if (_data == nil && _data.count<=0) {

        
    }
    return _data;
}

- (void)getCityDic
{
    _lists = [NSMutableArray new];
    _nameDic = [NSMutableDictionary new];
    
    _lists = [standfault objectForKey:@"cityArr"];
    if (_lists.count > 0) {
        for (int i = 0; i<[_lists count] ; i++) {
            NSString *name = [[_lists objectAtIndex:i] objectForKey:@"name"];
            //获取汉子的首字母
            //把中文转拼音
            NSMutableString *ms = [[NSMutableString alloc] initWithString:name];
            if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
                
            }
            if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
                
            }
            NSString *firstString = [[ms substringToIndex:1] uppercaseString];
            
            NSMutableArray * arr = [self.nameDic objectForKey:firstString];
            if (arr) {
                [arr addObject:name];
            }else{//如果没有 则需要创建一个添加到里面
                [self.nameDic setObject:[@[name] mutableCopy] forKey:firstString];
            }
        }
        
        _keys = [self.nameDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
        for (int i = 0; i<_keys.count; i++) {
            [self.arraySection addObject:_keys[i]];
        }

        [self.tableView reloadData];
    }else{
        [HttpRequest PostrequestUrl:@"/other/getAllCity" Dic:nil completion:^(NSDictionary *responseDic) {
            
            NSLog(@"responseDic11111:%@",responseDic);
            if ([responseDic[@"success"] boolValue]) {
                
                _lists = [responseDic objectForKey:@"data"];
                for (int i = 0; i<[[responseDic objectForKey:@"data"] count] ; i++) {
                    NSString *name = [[[responseDic objectForKey:@"data"] objectAtIndex:i] objectForKey:@"name"];
                    //获取汉子的首字母
                    //把中文转拼音
                    NSMutableString *ms = [[NSMutableString alloc] initWithString:name];
                    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
                        
                    }
                    if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
                        
                    }
                    NSString *firstString = [[ms substringToIndex:1] uppercaseString];
                    
                    NSMutableArray * arr = [self.nameDic objectForKey:firstString];
                    if (arr) {
                        [arr addObject:name];
                    }else{//如果没有 则需要创建一个添加到里面
                        [self.nameDic setObject:[@[name] mutableCopy] forKey:firstString];
                    }
                }
                
                _keys = [self.nameDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
                
                for (int i = 0; i<_keys.count; i++) {
                    [self.arraySection addObject:_keys[i]];
                }
                
                [standfault setObject:_lists forKey:@"cityArr"];
                [standfault synchronize];
                
                [self.tableView reloadData];
            }
        }];
    }
}

- (NSMutableArray *) cityData
{
    if (_cityData == nil) {
        _cityData = [[NSMutableArray alloc] init];
    }
    return _cityData;
}

//- (NSMutableArray *) localCityData
//{
//    if (_localCityData == nil) {
//        _localCityData = [[NSMutableArray alloc] init];
//        if (self.loactionCityName != nil) {
//
//
//            TLCity *city = nil;
//            for (TLCity *item in self.cityData) {
//                if ([item.cityName isEqualToString:self.loactionCityName]) {
//                    city = item;
//                    break;
//                }
//            }
//            if (city == nil) {
//                NSLog(@"Not Found City: %@", self.locationCityID);
//            }
//            else {
//                [_localCityData addObject:city];
//            }
//        }
//
//        if (self.locationCityID != nil) {
//            TLCity *city = nil;
//            for (TLCity *item in self.cityData) {
//                if ([item.cityName isEqualToString:self.locationCityID]) {
//                    city = item;
//                    break;
//                }
//            }
//            if (city == nil) {
//                NSLog(@"Not Found City: %@", self.locationCityID);
//            }
//            else {
//                [_localCityData addObject:city];
//            }
//        }
//    }
//    return _localCityData;
//}

- (NSMutableArray *) hotCityData
{
    if (_hotCityData == nil) {
        _hotCityData = [[NSMutableArray alloc] init];
        for (NSString *str in self.hotCitys) {
            if (str == nil) {
                NSLog(@"Not Found City1: %@", str);
            }
            else {
                [_hotCityData addObject:str];
            }
        }
    }
    return _hotCityData;
}

- (NSMutableArray *) commonCityData
{
    if (_commonCityData == nil) {
        _commonCityData = [[NSMutableArray alloc] init];
        for (NSString *str in self.commonCitys) {

            if (str == nil) {
                NSLog(@"Not Found City2: %@", str);
            }
            else {
                [_commonCityData addObject:str];
            }
        }
    }
    return _commonCityData;
}

- (NSMutableArray *) arraySection
{
    if (_arraySection == nil) {
        _arraySection = [[NSMutableArray alloc] initWithObjects: @"最近", @"最热", nil];
    }
    return _arraySection;
}

- (NSMutableArray *) commonCitys
{
    if (_commonCitys == nil) {
        NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:COMMON_CITY_DATA_KEY];
        _commonCitys = (array == nil ? [[NSMutableArray alloc] init] : [[NSMutableArray alloc] initWithArray:array copyItems:YES]);
    }
    return _commonCitys;
}

@end
